#!/usr/bin/env python
#coding:utf-8
#__author__="ybh"
import sys,os
import requests
import json
from datetime import datetime
import time
from aliyunsdkcore.client import AcsClient
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest
basedir = '/'.join(__file__.split("/")[:-2])
sys.path.append(basedir)
os.environ['DJANGO_SETTING_MODULE']='CrazyEye.settings'
from CrazyEye import settings
import django
django.setup()
from web import models
from django.db.models import Q

zone_list={
    'cn-qingdao':'华北1',
    'cn-beijing':'华北2',
    'cn-zhangjiakou':'华北3',
    'cn-huhehaote':'华北5',
    'cn-hangzhou':'华东1',
    'cn-shanghai':'华东2',
    'cn-shenzhen':'华南1',
    'cn-hongkong':'香港'
}

def main():
    account_list=models.Account.objects.filter(access_id__isnull=False,product='aliyun').exclude(access_id__exact='')
    for account in account_list:
        for zone in zone_list.keys():
            get_ecsinfo(account,zone)


def get_ecsinfo(account,zone):
    client = AcsClient(account.access_id,account.access_secret,zone)
    request = DescribeInstancesRequest.DescribeInstancesRequest()
    request.set_PageSize(10)
    response = client.do_action_with_exception(request)
    response=json.loads(response)
    ecs_list=response['Instances']['Instance']
    delete_ecs(ecs_list, account, zone)
    for ecs in ecs_list:
        ip=ecs['PublicIpAddress']['IpAddress'][0]
        mem=int(int(ecs['Memory'])/1024)
        cpu=ecs['Cpu']
        bandwidth=ecs['InternetMaxBandwidthOut']
        try:
            hostobj=models.Hosts.objects.get(ip_addr=ip)
        except Exception as e:
            idcobj=models.IDC.objects.get(name=zone_list[zone])
            hostobj=models.Hosts(hostname=ip,ip_addr=ip,idc=idcobj,account=account)
            hostobj.save()
        if hostobj:
            try:
                hinfoobj=models.HostInfo.objects.get(host=hostobj)
                hinfoobj.mem=mem
                hinfoobj.cpu=cpu
                hinfoobj.bandwidth=bandwidth
            except Exception as e:
                hinfoobj=models.HostInfo(host=hostobj,mem=mem,cpu=cpu,bandwidth=bandwidth)
                try:
                    host_user=models.HostUsers.objects.get(username='root')
                    bindhostobj=models.BindHosts(host=hostobj,host_user=host_user)
                    bindhostobj.save()
                except Exception as e:
                    pass
            hinfoobj.save()


def delete_ecs(ecs_list,account,zone):
    ecs_ip_list=[ecs['PublicIpAddress']['IpAddress'][0] for ecs in ecs_list]
    host_list=models.Hosts.objects.filter(account=account,idc__name=zone_list[zone])
    host_ip_list=[host.ip_addr for host in host_list]
    for host_ip in host_ip_list:
        if host_ip not in ecs_ip_list:
            models.Hosts.objects.get(ip_addr=host_ip).delete()

if __name__=='__main__':
    main()
